package net.toocruel.iqismart.web.controller.core;

import net.toocruel.iqismart.entity.common.Category;
import net.toocruel.iqismart.entity.constants.CategoryVisibility;
import net.toocruel.iqismart.entity.constants.SourceType;
import net.toocruel.iqismart.entity.core.Article;
import net.toocruel.iqismart.entity.core.Comment;
import net.toocruel.iqismart.entity.setting.Setting;
import net.toocruel.iqismart.service.UserService;
import net.toocruel.iqismart.service.core.*;
import net.toocruel.iqismart.service.exception.BusinessException;
import net.toocruel.iqismart.utils.FileUploadUtils;
import net.toocruel.iqismart.web.controller.base.AbstractBaseController;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("article")
public class ArticleController extends AbstractBaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private TagService tagService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private AnswerService answerService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private FileUploadUtils fileUploadUtils;

    @GetMapping("create")
    public String create(HttpServletRequest request,
                         Article article){
        //准备分类数据
        List<Category> categorys = categoryService.findByVisibilityAndRoles(CategoryVisibility.questions,getCurrentUser());
        request.setAttribute("categorys",categorys);

        //seoTitle
        request.setAttribute("seoTitle","撰写文章 - "+Setting.SETTING.getWebsite().getName());

        return getTemplate("create");
    }

    @PostMapping("create")
    public String doCreate(@Valid Article article, BindingResult bindingResult,
                           @RequestParam("logoFile") MultipartFile logoFile,
                           HttpServletRequest request, HttpServletResponse response){
        List<FieldError> allErrors = new ArrayList<>();
        bindingResult.getFieldErrors().stream().forEach(fieldError -> {
            if(!fieldError.getField().equals("category")){
                allErrors.add(fieldError);
            }
        });

        if(CollectionUtils.isEmpty(allErrors)){

            if (!logoFile.isEmpty()) {
                try {
                    String logo = fileUploadUtils.upload(logoFile.getInputStream(), logoFile.getOriginalFilename());
                    article.setLogo(logo);
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new BusinessException("文件上传失败");
                }


            }

            try {
                articleService.postArticle(article);
                return "redirect:/article/"+article.getId();
            } catch (Exception e) {
                e.printStackTrace();
                request.setAttribute("error",e);
            }
        }
        return  getTemplate("create");
    }

    @GetMapping("edit/{id}")
    public ModelAndView edit(@PathVariable  Long id,HttpServletRequest request){

        Article article = articleService.findById(id);

        //准备分类数据
        List<Category> categorys = categoryService.findByVisibilityAndRoles(CategoryVisibility.questions,getCurrentUser());
        request.setAttribute("categorys",categorys);

        //seoTitle
        request.setAttribute("seoTitle","编辑文章 - "+Setting.SETTING.getSeo().getQuestionTitle());

        return new ModelAndView(getTemplate("edit"),"article",article);
    }

    @PostMapping("edit/{id}")
    public ModelAndView edit(@PathVariable  Long id,@Valid Article article, BindingResult bindingResult,
                             @RequestParam("logoFile") MultipartFile logoFile,
                            HttpServletRequest request, HttpServletResponse response){

        if(!bindingResult.hasErrors()){
            try {
                if (!logoFile.isEmpty()) {
                    String logo = fileUploadUtils.upload(logoFile.getInputStream(), logoFile.getOriginalFilename());
                    article.setLogo(logo);
                }
                articleService.editArticle(article);

                return new ModelAndView("redirect:/article/"+article.getId());
            } catch (Exception e) {
                e.printStackTrace();
                request.setAttribute("error",e);
            }
        }


        ModelAndView modelAndView = new ModelAndView(getTemplate("edit"), "article", article);
        return modelAndView;
    }

    @GetMapping("{id}")
    public ModelAndView detail(@PathVariable Long id,@RequestParam(defaultValue = "createdAtDesc") String sort, HttpServletRequest request){

        Article article = articleService.findById(id);



        articleService.addViews(article);


        ModelAndView modelAndView = new ModelAndView(getTemplate("detail"), "article", article);
        modelAndView.addObject("comment",new Comment());
        modelAndView.addObject("topUsers",articleService.getTopUsers());

        //seoTitle
        String seoTitle = new String(Setting.SETTING.getSeo().getArticleTitle());
        seoTitle = seoTitle.replace("{wzbt}", article.getTitle());
        seoTitle = seoTitle.replace("{wzmc}",Setting.SETTING.getWebsite().getName());
        modelAndView.addObject("seoTitle",seoTitle);

        return modelAndView;
    }

    @GetMapping("{id}/comments")
    public ModelAndView comments(@PathVariable Long id,
                                 HttpServletRequest request,
                                 @RequestParam(defaultValue = "10000000") int size,
                                 @RequestParam(defaultValue = "1") int page,
                                 @RequestParam(defaultValue = "id") String sortBy,
                                 @RequestParam(defaultValue = "asc") String sortOrder){

        Page<Comment> commentPage = commentService.getCommonList(SourceType.article, id, new PageRequest(page - 1, size, new Sort(Sort.Direction.fromString(sortOrder), sortBy)));

        return new ModelAndView(getTemplate("question","commentList"),"comments",commentPage.getContent());
    }

    @Override
    protected String getModule() {
        return "article";
    }
}
